﻿layui.define(['jquery'], function (exports) {
    var $ = layui.jquery;

    var emojiUtil = {
        init: function (setting) {
            var emojiParam = {
                textAreaEle: '.noticeAdvertis',
                evokeBtn: '.face-advertis',
                emojiPanel: '.facePanel',
                timestamp: (new Date()).valueOf()
            };
            
            var emotions = new Array();
            var categorys = new Array();// 分组
            var uSinaEmotionsHt = new Hashtable();
            initData(emotions, categorys, uSinaEmotionsHt);
        
            $.extend(emojiParam, setting);

            $.fn.extend({
                insertContent: function (myValue, t) {
                    var $t = $(this)[0];
                    if (document.selection) { //ie
                        this.focus();
                        var sel = document.selection.createRange();
                        sel.text = myValue;
                        this.focus();
                        sel.moveStart('character', -l);
                        var wee = sel.text.length;
                        if (arguments.length == 2) {
                            var l = $t.value.length;
                            sel.moveEnd("character", wee + t);
                            t <= 0 ? sel.moveStart("character", wee - 2 * t - myValue.length) : sel.moveStart("character", wee - t - myValue.length);

                            sel.select();
                        }
                    } else if ($t.selectionStart || $t.selectionStart == '0') {
                        var startPos = $t.selectionStart;
                        var endPos = $t.selectionEnd;
                        var scrollTop = $t.scrollTop;
                        $t.value = $t.value.substring(0, startPos) + myValue + $t.value.substring(endPos, $t.value.length);
                        this.focus();
                        $t.selectionStart = startPos + myValue.length;
                        $t.selectionEnd = startPos + myValue.length;
                        $t.scrollTop = scrollTop;
                        if (arguments.length == 2) {
                            $t.setSelectionRange(startPos - t, $t.selectionEnd + t);
                            this.focus();
                        }
                    }
                    else {
                        this.value += myValue;
                        this.focus();
                    }
                }
            })
            $.fn.sinaEmotion = function (target, emojiParam) {
                var cat_current;
                var cat_page;
                var index = 0;
                $(this).click(function (event) {
                    event.stopPropagation();
                    var eTop = target.offset().top + target.height() + 20 + 'px';
                    var eLeft =0

                    var w = $(window).width();

                    $(emojiParam.emojiPanel).append('<div id="emotions" class="emotions emotions_' + emojiParam.timestamp+'"></div>');

                    $(".emotions_" + emojiParam.timestamp).css({ top: eTop + 'px', left: (eLeft) + 'px' });

                    $(".emotions_" + emojiParam.timestamp).html('<div>正在加载，请稍候...</div>');
                    $(".emotions_" + emojiParam.timestamp).click(function (event) {
                        event.stopPropagation();
                    });
                    $(".emotions_" + emojiParam.timestamp).html(
                        '<div class="categorys"></div>' +
                        '<div class="cont"></div>');

                    showCategorys();
                    showEmotions();
                    var ctLength = $('.categorys a').length;
                    var ctWidth = $('.categorys').width();
                    $('.categorys a').css({ 'width': 100 + '%', 'textAlign': 'center' })

                    var emo1 = $(emojiParam.emojiPanel + " .emotions_" + emojiParam.timestamp + ":gt(0)");
                    //emo.remove();

                    emo1.remove();
                });
                $.fn.insertText = function (text) {
                    this.each(function () {
                        if (this.tagName !== 'INPUT' && this.tagName !== 'TEXTAREA') { return; }
                        if (document.selection) {
                            this.focus();
                            var cr = document.selection.createRange();
                            cr.text = text;
                            cr.collapse();
                            cr.select();
                        } else if (this.selectionStart || this.selectionStart == '0') {
                            var
                                start = this.selectionStart,
                                end = this.selectionEnd;
                            this.value = this.value.substring(0, start) + text + this.value.substring(end, this.value.length);
                            this.selectionStart = this.selectionEnd = start + text.length;
                        } else {
                            this.value += text;
                        }
                    });
                    return this;
                }
                function showCategorys() {

                    var page = arguments[0] ? arguments[0] : 0;
                    if (page < 0 || page >= categorys.length / 5) {
                        return;
                    }
                    $('#emotions .categorys').html('');
                    cat_page = page;
                    for (var i = page * 5; i < (page + 1) * 5 && i < categorys.length; ++i) {
                        $('#emotions .categorys').append($('<a href="javascript:void(0);">' + categorys[i] + '</a>'));
                    }
                    $('#emotions .categorys a').click(function () {
                        showEmotions($(this).text());
                    });
                    $('#emotions .categorys a').each(function () {
                        if ($(this).text() == cat_current) {
                            $(this).addClass('current');
                        }
                    });

                }
                function showEmotions() {
                    var category = arguments[0] ? arguments[0] : '默认';
                    var page = arguments[1] ? arguments[1] - 1 : 0;
                    $('#emotions .cont').html('');
                    cat_current = category;
                    for (var i = 0; i < emotions[category].length; ++i) {
                        $('#emotions .cont').append($('<a href="javascript:void(0);" title="' + emotions[category][i].name + '"><img src="' + emotions[category][i].icon + '" alt="' + emotions[category][i].name + '" width="22" height="22" /></a>'));
                    }
                    $('#emotions .cont a').click(function () {
                        var Img = $(this).find('img').attr('src')
                        var Atr = $(this).find('img').attr('alt')
                        //alert(target.tagName)
                        //<img src="' + Img + '" title="' + Atr + '"/>
                        //target.append($("<span>"+Atr+"</span>"))
                        target.insertText($(this).attr('title'));
                        //点击单个
                        // $(".emotions").remove();
                        //$(".emotions").hide();
                        $('.face-icon').addClass('brow-up').removeClass('brow-down');
                        $(emojiParam.evokeBtn).addClass('advertis-up').removeClass('advertis-down');
                        $('.face-timing').addClass('timing-up').removeClass('timing-down');
                    });

                    $('#emotions .categorys a.current').removeClass('current');
                    $('#emotions .categorys a').each(function () {
                        if ($(this).text() == category) {
                            $(this).addClass('current');
                        }
                    });
                }
            }
            initElement(emojiParam);
        }
    };

    function Hashtable() {
        this._hash = new Object();
        this.put = function (key, value) {
            if (typeof (key) != "undefined") {
                if (this.containsKey(key) == false) {
                    this._hash[key] = typeof (value) == "undefined" ? null : value;
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        }
        this.remove = function (key) { delete this._hash[key]; }
        this.size = function () { var i = 0; for (var k in this._hash) { i++; } return i; }
        this.get = function (key) { return this._hash[key]; }
        this.containsKey = function (key) { return typeof (this._hash[key]) != "undefined"; }
        this.clear = function () { for (var k in this._hash) { delete this._hash[k]; } }
    }

    var initData = function (emotions, categorys, uSinaEmotionsHt) {
        $.ajax({
            dataType: 'json',
            url: '/Scripts/Common/qqFace.js',
            async: false,
            success: function (response) {
                var data = response;

                for (var i in data) {
                    if (data[i].category == '') {
                        data[i].category = '默认';
                    }
                    if (emotions[data[i].category] == undefined) {
                        emotions[data[i].category] = new Array();
                        categorys.push(data[i].category);
                    }
                    emotions[data[i].category].push({
                        name: data[i].phrase,
                        icon: data[i].icon
                    });
                    uSinaEmotionsHt.put(data[i].phrase, data[i].icon);
                }
            }
        });
    }

    var initElement = function (emojiParam) {
        $.fn.qqFace = function (a, b, c, d, f) {
            $(a).sinaEmotion($(b), emojiParam);

            $(a).on('click', function () {
              
                $(".emotions").hide();
                if ($(this).hasClass(c)) {
                    $(this).addClass(d).removeClass(c);
                    $(f).show();
                } else {
                    $(this).addClass(c).removeClass(d);
                    $(f).hide();
                }
            })
            $(document).click(function (event) {
                event.stopPropagation();
                $(f).hide();
                $(a).addClass(c).removeClass(d);
            })
        }

        $.fn.qqFace(emojiParam.evokeBtn, emojiParam.textAreaEle, "advertis-up", "advertis-down", ".emotions_" + emojiParam.timestamp)
    }

    //输出test接口
    exports('emojiUtil', emojiUtil);
});
